﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.ComponentModel;
using System.Data.SqlClient;

namespace Owners
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private CollectionViewSource _clientViewSource = null;
        private CollectionViewSource _carrierCodeViewSource = null;
        SalesManagerEntities _sme;
        private List<tblMiscDef> _miscDefs;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _sme = new SalesManagerEntities();

            _clientViewSource = (CollectionViewSource)FindResource("ClientListViewSource");
            _clientViewSource.Source = from c in _sme.tblOwner select c;
            _clientViewSource.View.CurrentChanged += new EventHandler(ClientView_CurrentChanged);

            _carrierCodeViewSource = (CollectionViewSource)FindResource("CarrierCodeViewSource");
            var carrierCodeList = (from c in _sme.codeCarrier select new { c.CarrierCode, c.Description }).ToList();
            carrierCodeList.Add(new { CarrierCode = (string)null, Description = string.Empty });
            _carrierCodeViewSource.Source = carrierCodeList;

            ClientView_CurrentChanged(null, null);
        }

        void ClientView_CurrentChanged(object sender, EventArgs e)
        {
            if (cmbClient.SelectedItem == null)
                return;
            Int32 ownerID = ((tblOwner)cmbClient.SelectedItem).OwnerID;
            var accountList = (from c in _sme.tblAccount
                                        where c.Name != null
                                        && (c.OwnerID == ownerID || c.OwnerID == null)
                                        select new { AccountID=(Int32?)c.AccountID, c.Name }).ToList();
            accountList.Add( new { AccountID = (Int32?)null, Name = string.Empty } );

            ((CollectionViewSource)FindResource("CashAccountViewSource")).Source = accountList;
            cmbCashAccount.SetBinding(ComboBox.SelectedValueProperty, "CashAccountID");
            ((CollectionViewSource)FindResource("ProductRevenueAccountViewSource")).Source = accountList;
            cmbProductRevenueAccount.SetBinding(ComboBox.SelectedValueProperty, "ProductRevenueAccountID");
            ((CollectionViewSource)FindResource("InventoryAccountViewSource")).Source = accountList;
            cmbInventoryAccount.SetBinding(ComboBox.SelectedValueProperty, "InventoryAccountID");
            ((CollectionViewSource)FindResource("CostOfGoodsSoldAccountViewSource")).Source = accountList;
            cmbCostOfGoodsSoldAccount.SetBinding(ComboBox.SelectedValueProperty, "CostOfGoodsSoldAccountID");
            ((CollectionViewSource)FindResource("CostOfGoodsAdjustmentsAccountViewSource")).Source = accountList;
            cmbCostOfGoodsAdjustmentAccount.SetBinding(ComboBox.SelectedValueProperty, "CostOfGoodsAdjustmentAccountID");
            ((CollectionViewSource)FindResource("ShippingCostAccountViewSource")).Source = accountList;
            cmbShippingCostAccount.SetBinding(ComboBox.SelectedValueProperty, "ShippingCostAccountID");
            ((CollectionViewSource)FindResource("ShippingRevenueAccountViewSource")).Source = accountList;
            cmbShippingRevenueAccount.SetBinding(ComboBox.SelectedValueProperty, "ShippingRevenueAccountID");
            ((CollectionViewSource)FindResource("TaxRevenueAccountViewSource")).Source = accountList;
            cmbTaxRevenueAccount.SetBinding(ComboBox.SelectedValueProperty, "TaxRevenueAccountID");
            ((CollectionViewSource)FindResource("MiscExpenseAccountViewSource")).Source = accountList;
            cmbMiscExpenseAccount.SetBinding(ComboBox.SelectedValueProperty, "MiscExpenseAccountID");

            tabUserDefined.Items.Clear();
            _miscDefs = (from c in _sme.tblMiscDef
                         where c.OwnerID == ownerID || c.OwnerID == null
                         select c).ToList();

            foreach (string tableName in new string[] { "tblCustomer", "tblOrderHeader", "tblProduct", "tblRMAReturn", "tblInventoryTransactionDetail" })
            {
                TabItem newTab = new TabItem();
                newTab.Header = tableName;
                tabUserDefined.Items.Add(newTab);
                Grid newGrid = new Grid();
                newTab.Content = newGrid;
                newGrid.ColumnDefinitions.Add(new ColumnDefinition());
                newGrid.ColumnDefinitions.Add(new ColumnDefinition());
                newGrid.ColumnDefinitions.Add(new ColumnDefinition());

                RowDefinition newRow = new RowDefinition();
                newRow.Height = new GridLength(24);
                newGrid.RowDefinitions.Add(newRow);

                Label lbl = new Label();
                lbl.Content = "Name";
                Grid.SetRow(lbl, 0);
                Grid.SetColumn(lbl, 1);
                newGrid.Children.Add(lbl);

                lbl = new Label();
                lbl.Content = "Tooltip";
                Grid.SetRow(lbl, 0);
                Grid.SetColumn(lbl, 2);
                newGrid.Children.Add(lbl);

                int udCount = (tableName == "tblProduct") ? 9 :
                    (tableName == "tblRMAReturn") ? 5 :
                    (tableName == "tblCustomer") ? 9 :
                    (tableName == "tblOrderHeader") ? 9 :
                    (tableName == "tblInventoryTransactionDetail") ? 4 :
                    0;
                for (int i = 0; i < udCount; i++)
                {
                    newRow = new RowDefinition();
                    newRow.Height = new GridLength(24);
                    newGrid.RowDefinitions.Add(newRow);
                    lbl = new Label();
                    lbl.Content = "UserDefined" + (i+1).ToString();
                    Grid.SetRow(lbl, i+1);
                    newGrid.Children.Add(lbl);

                    tblMiscDef miscDef = _miscDefs.Where(c => c.TableName.Trim() == tableName && c.FieldNumber == i + 1).FirstOrDefault();

                    TextBox tb = new TextBox();
                    tb.Name = "Name_" + tableName + "_" + (i + 1).ToString();
                    tb.Text = (miscDef == null) ? null : miscDef.Name;
                    Grid.SetRow(tb, i+1);
                    Grid.SetColumn(tb, 1);
                    newGrid.Children.Add(tb);
                    tb.IsReadOnly = (miscDef == null) ? false :
                        (miscDef.OwnerID == null) ? true :
                        false;
                    tb.LostFocus += new RoutedEventHandler(UserDefined_LostFocus);

                    tb = new TextBox();
                    tb.Name = "Tooltip_" + tableName + "_" + (i + 1).ToString();
                    tb.Text = (miscDef == null) ? null : miscDef.Tooltip;
                    Grid.SetRow(tb, i+1);
                    Grid.SetColumn(tb, 2);
                    newGrid.Children.Add(tb);
                    tb.IsReadOnly = (miscDef == null) ? false :
                        (miscDef.OwnerID == null) ? true :
                        false;
                    tb.LostFocus += new RoutedEventHandler(UserDefined_LostFocus);
                }
            }
        }

        void UserDefined_LostFocus(object sender, RoutedEventArgs e)
        {
            // Break the control name into its component parts
            Int32 ownerID = ((tblOwner)cmbClient.SelectedItem).OwnerID;
            string[] parts = ((FrameworkElement)e.Source).Name.Split(new char[] { '_' });
            string field = parts[0];
            string tableName = parts[1];
            int index = int.Parse(parts[2]);

            // Try to get the matching MiscDef from the database
            tblMiscDef miscDef =  _miscDefs.Where(c=>c.TableName.Trim() == tableName && c.FieldNumber == index).FirstOrDefault();

            // If the MiscDef doesn't exist yet then create it.
            if (miscDef == null && ((TextBox)e.Source).Text.Trim() != string.Empty)
            {
                miscDef = new tblMiscDef();
                miscDef.OwnerID = ownerID;
                miscDef.TableName = tableName;
                miscDef.FieldNumber = index;
                _sme.AddTotblMiscDef(miscDef);
                _miscDefs.Add(miscDef);
            }
            if (field == "Name" && miscDef != null)
            {
                if (((TextBox)e.Source).Text.Trim() == string.Empty)
                {
                    _sme.tblMiscDef.DeleteObject(miscDef);
                    _miscDefs.Remove(miscDef);
                }
                else
                    miscDef.Name = ((TextBox)e.Source).Text;
            }
            if (field == "Tooltip" && miscDef != null)
                miscDef.Tooltip = ((TextBox)e.Source).Text;
        }

        private void brnSave_Click(object sender, RoutedEventArgs e)
        {
            _sme.SaveChanges();
            Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_sme.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified).Count() > 0)
            {
                MessageBoxResult result = MessageBox.Show("Do you want to save changes before closing?", "Save changes?", MessageBoxButton.YesNoCancel);
                if (result == MessageBoxResult.Cancel)
                    e.Cancel = true;
                if (result == MessageBoxResult.Yes)
                    _sme.SaveChanges();
            }
        }

        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            DialogNewOwner dlg = new DialogNewOwner();
            if ((bool)dlg.ShowDialog())
            {
                SqlConnection conn = (SqlConnection)((System.Data.EntityClient.EntityConnection)_sme.Connection).StoreConnection;
                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();
                SqlCommand cmm = conn.CreateCommand();
                cmm.CommandType = System.Data.CommandType.StoredProcedure;
                cmm.CommandText = "spCreateNewCompany";
                cmm.Parameters.Add(new SqlParameter("@ShortName", dlg.ShortName));
                cmm.Parameters.Add(new SqlParameter("@LongName", dlg.LongName));
                cmm.Parameters.Add(new SqlParameter("@ReturnValue", System.Data.SqlDbType.BigInt)).Direction = System.Data.ParameterDirection.ReturnValue;
                cmm.ExecuteNonQuery();

                Int32 ownerID = (Int32)cmm.Parameters["@ReturnValue"].Value;
                _clientViewSource.Source = from c in _sme.tblOwner select c;
                tblOwner newOwner = (tblOwner)_sme.GetObjectByKey(new EntityKey("SalesManagerEntities.tblOwner", "OwnerID", ownerID));
                _clientViewSource.View.MoveCurrentTo(newOwner);
                txtShortName.Focus();
                txtShortName.SelectAll();
            }
        }
    }
}
